<template>
  <div class="menu-manage">
    <el-row :gutter="20">
      <el-col :span="12">
        <el-card>
          <div class="header-bar">
            <span>菜单列表</span>
            <el-button type="primary" size="small" @click="openAddMenu">新增菜单</el-button>
          </div>
          <el-table :data="menuList" border style="width: 100%">
            <el-table-column prop="id" label="ID" width="60"/>
            <el-table-column prop="name" label="菜单名称"/>
            <el-table-column prop="path" label="路由路径"/>
            <el-table-column prop="icon" label="图标"/>
            <el-table-column prop="sort" label="排序" width="80"/>
            <el-table-column prop="status" label="状态" width="80">
              <template #default="scope">
                <el-tag :type="scope.row.status === 1 ? 'success' : 'info'">
                  {{ scope.row.status === 1 ? '启用' : '禁用' }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column label="操作" width="180">
              <template #default="scope">
                <el-button size="small" @click="openEditMenu(scope.row)">编辑</el-button>
                <el-button size="small" type="danger" @click="handleDeleteMenu(scope.row)">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-card>
      </el-col>
      <el-col :span="12">
        <el-card>
          <div class="header-bar">
            <span>角色菜单分配</span>
          </div>
          <el-form :inline="true">
            <el-form-item label="选择角色">
              <el-select v-model="selectedRoleId" placeholder="请选择角色" @change="fetchRoleMenuIds"
                         style="width: 150px;">
                <el-option v-for="role in roleList" :key="role.id" :label="role.name" :value="role.id"/>
              </el-select>
            </el-form-item>
          </el-form>
          <el-checkbox-group v-model="checkedMenuIds" style="margin-top: 10px;">
            <el-checkbox v-for="menu in menuList" :key="menu.id" :label="menu.id">
              {{ menu.name }}
            </el-checkbox>
          </el-checkbox-group>
          <div style="margin-top: 20px;">
            <el-button type="primary" :disabled="!selectedRoleId" @click="handleAssignMenu">保存分配</el-button>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 新增/编辑菜单弹窗 -->
    <el-dialog v-model="menuDialogVisible" :title="menuForm.id ? '编辑菜单' : '新增菜单'">
      <el-form :model="menuForm" label-width="80px">
        <el-form-item label="菜单名称">
          <el-input v-model="menuForm.name"/>
        </el-form-item>
        <el-form-item label="路由路径">
          <el-input v-model="menuForm.path"/>
        </el-form-item>
        <el-form-item label="图标">
          <el-input v-model="menuForm.icon"/>
        </el-form-item>
        <el-form-item label="排序">
          <el-input-number v-model="menuForm.sort" :min="0"/>
        </el-form-item>
        <el-form-item label="状态">
          <el-switch v-model="menuForm.status" :active-value="1" :inactive-value="0"/>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="menuDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSaveMenu">保存</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import {ref, onMounted} from 'vue'
import {ElMessage, ElMessageBox} from 'element-plus'
import {getMenuList, addMenu, updateMenu, deleteMenu, assignMenuToRole, getRoleMenuIds} from '@/api/admin/menu'
import {getRoleList} from '@/api/admin/role'

const menuList = ref([])
const roleList = ref([])
const selectedRoleId = ref()
const checkedMenuIds = ref([])

const menuDialogVisible = ref(false)
const menuForm = ref({id: null, name: '', path: '', icon: '', sort: 0, status: 1})

const fetchMenus = async () => {
  const res = await getMenuList()
  if (res.code === 200) {
    menuList.value = res.data
  }
}

const fetchRoles = async () => {
  const res = await getRoleList()
  if (res.code === 200) {
    roleList.value = res.data
  }
}

const fetchRoleMenuIds = async () => {
  if (!selectedRoleId.value) return
  const res = await getRoleMenuIds(selectedRoleId.value)
  if (res.code === 200) {
    checkedMenuIds.value = res.data
  }
}

const openAddMenu = () => {
  menuForm.value = {id: null, name: '', path: '', icon: '', sort: 0, status: 1}
  menuDialogVisible.value = true
}

const openEditMenu = (row) => {
  menuForm.value = {...row}
  menuDialogVisible.value = true
}

const handleSaveMenu = async () => {
  if (!menuForm.value.name || !menuForm.value.path) {
    ElMessage.warning('菜单名称和路由路径不能为空')
    return
  }
  let res
  if (menuForm.value.id) {
    res = await updateMenu(menuForm.value)
  } else {
    res = await addMenu(menuForm.value)
  }
  if (res.code === 200) {
    ElMessage.success('保存成功')
    menuDialogVisible.value = false
    fetchMenus()
  } else {
    ElMessage.error(res.msg || '保存失败')
  }
}

const handleDeleteMenu = (row) => {
  ElMessageBox.confirm('确定要删除该菜单吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    const res = await deleteMenu(row.id)
    if (res.code === 200) {
      ElMessage.success('删除成功')
      fetchMenus()
    } else {
      ElMessage.error(res.msg || '删除失败')
    }
  }).catch(() => {
  })
}

const handleAssignMenu = async () => {
  if (!selectedRoleId.value) return
  const res = await assignMenuToRole(selectedRoleId.value, checkedMenuIds.value)
  if (res.code === 200) {
    ElMessage.success('分配成功')
  } else {
    ElMessage.error(res.msg || '分配失败')
  }
}

onMounted(() => {
  fetchMenus()
  fetchRoles()
})
</script>

<style scoped>
.menu-manage {
  padding: 20px;
}

.header-bar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 10px;
}
</style>
